import os
import concurrent.futures

# 删除某目录下的所有文件和子目录

# 定义要删除的目录路径
root_directory = '/Volumes/fzt'
# 递归获取目录下的所有文件和子目录
def get_all_files_and_dirs(path):
    file_paths = []
    for root, dirs, files in os.walk(path):
        for file in files:
            file_paths.append(os.path.join(root, file))
        for dir in dirs:
            subdir_path = os.path.join(root, dir)
            file_paths.extend(get_all_files_and_dirs(subdir_path))  # 递归添加子目录中的文件
            file_paths.append(subdir_path)  # 将子目录添加到列表，以便后续删除
    return file_paths

# 删除文件或目录
def delete_file_or_dir(file_path):
    try:
        if os.path.isfile(file_path):
            os.remove(file_path)
            print(f"Deleted file: {file_path}")
        elif os.path.isdir(file_path):
            os.rmdir(file_path)
            print(f"Deleted directory: {file_path}")
    except Exception as e:
        print(f"Error deleting {file_path}: {e}")

# 获取所有需要删除的文件和目录路径
all_paths = get_all_files_and_dirs(root_directory)

# 使用多线程删除文件和目录
with concurrent.futures.ThreadPoolExecutor() as executor:
    # 反向排序路径列表，以确保先删除子目录
    all_paths.sort(reverse=True)
    # 提交删除任务到线程池
    futures = {executor.submit(delete_file_or_dir, path) for path in all_paths}
    # 等待所有任务完成
    concurrent.futures.wait(futures)

print("All files and directories have been deleted.")